package com.amokgames.tictactoe;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;

public class Piece extends Button {
	Paint paint;
	float radius;
	
	GameEngine gameEngine;
	int x, y;
	private TicTacToe parent;
	
	public void setup(TicTacToe parent, GameEngine gameEngine, int x, int y) {
		this.parent = parent;
		this.gameEngine = gameEngine;
		this.x = x;
		this.y = y;
		
		reset();

		paint = new Paint();
		paint.setColor(Color.BLACK);
		paint.setStrokeWidth(5);
		paint.setStyle(Style.STROKE);
		
		setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	((Piece)v).handleClick();
            }
        });
	}

	void handleClick() {
		gameEngine.handleClick(x, y);
		parent.updateMessage();
	}
	
	public void reset() {
		invalidate();
	}
	
	public Piece(Context context) {
		super(context);
	}
	public Piece (Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	public Piece (Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	public void onDraw(Canvas canvas) {
		if(gameEngine == null)
			return;
		if(getWidth() > getHeight())
			radius = (getHeight() / 2) * 0.8f;
		else
			radius = (getWidth() / 2) * 0.8f;
		
		Turn state = gameEngine.getState(x, y);
		if(state == Turn.o)
			canvas.drawCircle(getWidth() / 2, getHeight() / 2, radius, paint);
		else if(state == Turn.x) {
			canvas.drawLine(0, getHeight(), getWidth(), 0, paint);
			canvas.drawLine(0, 0, getWidth(), getHeight(), paint);
		}
    }
}